package com.fenghongzhang.zhoukao2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main3Activity extends AppCompatActivity {
    private Button btn;
    private ListView lv;

    private List<Food.DataBean> data;

    private MyListAdapter myListAdapter ;
    private static final String TAG = "Main3Activity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        lv = (ListView) findViewById(R.id.lv);

        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAsyn().execute("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");
            }
        });

    }

    class MyAsyn extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = null;
                urlConnection = (HttpURLConnection) url.openConnection();
                Log.i(TAG, "doInBackground: ");
                if (urlConnection.getResponseCode() == 200){
                    InputStream inputStream = urlConnection.getInputStream();
                    StringBuffer stringBuffer = new StringBuffer();
                    byte[] bytes = new byte[1024];//10
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1){
                        String s = new String(bytes, 0, len);
                        stringBuffer.append(s);
                        Log.i(TAG, "doInBackground: "+stringBuffer.toString());
                    }
                    return stringBuffer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i(TAG, "onPostExecute: "+s);
            Gson gson = new Gson();
            Food food = gson.fromJson(s, Food.class);
            data = food.getData();
            //new 适配器listView
             myListAdapter = new MyListAdapter(Main3Activity.this, data);
            lv.setAdapter(myListAdapter);
        }
    }

}
